package org.harsh.common.net;

import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Created by liuhaibo on 2024/7/17.
 */
@Getter
@Slf4j
public abstract class PingResult {
    private List<String> lines;
    private String address;
    private int transmitted = -1;
    private int ttl = -1;
    private long time = -1;
    private int received = -1;
    private int payload = -1;
    private float rtt_min = -1;
    private float rtt_avg = -1;
    private float rtt_max = -1;
    private float rtt_mdev = -1;
    private float lossRate = 0;

    protected PingResult(List<String> pingOutput) {
        try {
            this.lines = pingOutput;
            transmitted = matchTransmitted(pingOutput);
            received = matchReceived(pingOutput);
            time = matchTime(pingOutput);

            rtt_min = matchRttMin(pingOutput);
            rtt_avg = matchRttAvg(pingOutput);
            rtt_max = matchRttMax(pingOutput);
            rtt_mdev = matchRttMdev(pingOutput);

            ttl = matchTTL(pingOutput);

            address = matchIP(pingOutput);

            payload = parsePayload(pingOutput);

            lossRate = matchLossRate(pingOutput);
        } catch (Exception e) {
            log.error("Ping result build error. Msg : ", e);
        }

    }

    public List<String> getLines() {
        return lines;
    }

    protected abstract int parsePayload(List<String> lines);

    protected abstract int matchTransmitted(List<String> lines);

    protected abstract int matchReceived(List<String> lines);

    protected abstract int matchTime(List<String> lines);

    protected abstract float matchRttMin(List<String> lines);

    protected abstract float matchRttAvg(List<String> lines);

    protected abstract float matchRttMax(List<String> lines);

    protected abstract float matchRttMdev(List<String> lines);

    protected abstract String matchIP(List<String> lines);

    protected abstract int matchTTL(List<String> lines);

    protected abstract float matchLossRate(List<String> lines);

    public abstract List<PingRequest> getRequests();

    @Override
    public String toString() {
        return "PingResult [address=" + address + ", transmitted="
                + transmitted + ", ttl=" + ttl + ", time=" + time
                + ", received=" + received + ", payload=" + payload
                + ", rtt_min=" + rtt_min + ", rtt_avg=" + rtt_avg
                + ", rtt_max=" + rtt_max + ", rtt_mdev=" + rtt_mdev + "]";
    }
}
